<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,量化投资,机器学习,回归分析,实操,泰坦尼克号,kaggle," />










<meta name="description" content="用kaggle上的泰坦尼克的数据来实操。https:&#x2F;&#x2F;www.kaggle.com&#x2F;c&#x2F;titanic&#x2F;overview在主页上下载了数据。任务:使用泰坦尼克号乘客数据建立机器学习模型，来预测乘客在海难中是否生存。在实际海难中，2224位乘客中有1502位遇难了。似乎有的乘客比其它乘客更有机会获救。本任务的目的就是找出哪类人更容易获救。数据集有两个，一个是训练数据集”train.csv”，另一个">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记19——回归分析:实操，泰坦尼克号乘客生还机会预测，线性回归方法。">
<meta property="og:url" content="https://zwdnet.github.io/2020/03/07/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B019%E2%80%94%E2%80%94%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90-%E5%AE%9E%E6%93%8D%EF%BC%8C%E6%B3%B0%E5%9D%A6%E5%B0%BC%E5%85%8B%E5%8F%B7%E4%B9%98%E5%AE%A2%E7%94%9F%E8%BF%98%E6%9C%BA%E4%BC%9A%E9%A2%84%E6%B5%8B%EF%BC%8C%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E6%96%B9%E6%B3%95%E3%80%82/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="用kaggle上的泰坦尼克的数据来实操。https:&#x2F;&#x2F;www.kaggle.com&#x2F;c&#x2F;titanic&#x2F;overview在主页上下载了数据。任务:使用泰坦尼克号乘客数据建立机器学习模型，来预测乘客在海难中是否生存。在实际海难中，2224位乘客中有1502位遇难了。似乎有的乘客比其它乘客更有机会获救。本任务的目的就是找出哪类人更容易获救。数据集有两个，一个是训练数据集”train.csv”，另一个">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/11.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/12.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/13.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/14.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/15.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/16.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-03-07T07:47:14.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="机器学习">
<meta property="article:tag" content="回归分析">
<meta property="article:tag" content="实操">
<meta property="article:tag" content="泰坦尼克号">
<meta property="article:tag" content="kaggle">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/03/07/量化投资学习笔记19——回归分析-实操，泰坦尼克号乘客生还机会预测，线性回归方法。/"/>





  <title>量化投资学习笔记19——回归分析:实操，泰坦尼克号乘客生还机会预测，线性回归方法。 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/03/07/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B019%E2%80%94%E2%80%94%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90-%E5%AE%9E%E6%93%8D%EF%BC%8C%E6%B3%B0%E5%9D%A6%E5%B0%BC%E5%85%8B%E5%8F%B7%E4%B9%98%E5%AE%A2%E7%94%9F%E8%BF%98%E6%9C%BA%E4%BC%9A%E9%A2%84%E6%B5%8B%EF%BC%8C%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E6%96%B9%E6%B3%95%E3%80%82/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记19——回归分析:实操，泰坦尼克号乘客生还机会预测，线性回归方法。</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-03-07T07:47:14+00:00">
                2020-03-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>用kaggle上的泰坦尼克的数据来实操。<br><a target="_blank" rel="noopener" href="https://www.kaggle.com/c/titanic/overview">https://www.kaggle.com/c/titanic/overview</a><br>在主页上下载了数据。<br>任务:使用泰坦尼克号乘客数据建立机器学习模型，来预测乘客在海难中是否生存。<br>在实际海难中，2224位乘客中有1502位遇难了。似乎有的乘客比其它乘客更有机会获救。本任务的目的就是找出哪类人更容易获救。<br>数据集有两个，一个是训练数据集”train.csv”，另一个是测试数据集”test.csv”。<br>官方推荐一个教程:<a target="_blank" rel="noopener" href="https://www.kaggle.com/alexisbcook/titanic-tutorial">https://www.kaggle.com/alexisbcook/titanic-tutorial</a><br>先照着来吧。<br>就是熟悉了整个结果上传流程，使用了随机树森林算法，结果正确率是77.551%，排9444位。<br>接下来就是我自己折腾了。<br>读取数据后，用info函数看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">print(train_data.info())</span><br><span class="line">print(test_data.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/01.png"><br>有三列数据有缺失值。先将数据可视化吧。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/02.png"><br>第一张是遇难者与获救者的比例，第二张是三个票价等级的人数，第三张是遇难者及获救者的年龄分布，第四张是按船票等级的年龄分布，最后一张是三个港口的登船人数。<br>再画一个不同船票等级的乘客的获救率。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/03.png"><br>可见高等级的获救率更高。<br>再画图看性别与获救的关系<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/04.png"><br>真是lady first<br>下面再看各个舱别的获救人数。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/05.png"><br>高等舱的女性生还率最高，其次是高等舱男性，低等舱男性生还率最低。<br>再看各港口登船的情况。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/06.png"><br>三个港口登船人数依次下降，死亡率差不多。<br>有堂兄弟妹，有子女父母对死亡率的影响。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">g = train_data.groupby([<span class="string">&quot;SibSp&quot;</span>, <span class="string">&quot;Survived&quot;</span>])</span><br><span class="line">df = pd.DataFrame(g.count()[<span class="string">&quot;PassengerId&quot;</span>])</span><br><span class="line">print(df)</span><br><span class="line">g = train_data.groupby([<span class="string">&quot;Parch&quot;</span>, <span class="string">&quot;Survived&quot;</span>])</span><br><span class="line">df = pd.DataFrame(g.count()[<span class="string">&quot;PassengerId&quot;</span>])</span><br><span class="line">print(df)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/07.png"><br>没看出啥来。<br>Cabin缺失数据太多，画图看看数据缺失的和有数据的两组死亡率是否有差别。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/08.png"><br>貌似有cabin记录的获救率高一些。<br>接下来就要清洗数据了，主要是处理缺失的数据，进行数据转换。<br>(下面参考了<a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_44451032/article/details/100103998">https://blog.csdn.net/weixin_44451032/article/details/100103998</a>)<br>先查看缺失值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">print(train_data.isnull().<span class="built_in">sum</span>())</span><br><span class="line">print(test_data.isnull().<span class="built_in">sum</span>())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/09.png"><br>主要是Age、Embarked和Cabin三个字段的缺失数据较多。<br>Age用年龄中位数填充，登船地点填充为众数，Cabin则采用因子化，即根据有无Cabin数据分为两类。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">train_data[<span class="string">&quot;Age&quot;</span>].fillna(train_data[<span class="string">&quot;Age&quot;</span>].median(), inplace = <span class="literal">True</span>)</span><br><span class="line">test_data[<span class="string">&quot;Age&quot;</span>].fillna(test_data[<span class="string">&quot;Age&quot;</span>].median(), inplace = <span class="literal">True</span>)</span><br><span class="line">train_data[<span class="string">&quot;Embarked&quot;</span>] = train_data[<span class="string">&quot;Embarked&quot;</span>].fillna(<span class="string">&#x27;S&#x27;</span>)</span><br><span class="line">train_data.loc[(train_data.Cabin.notnull()), <span class="string">&quot;Cabin&quot;</span>] = <span class="number">1</span></span><br><span class="line">train_data.loc[(train_data.Cabin.isnull()), <span class="string">&quot;Cabin&quot;</span>] = <span class="number">0</span></span><br><span class="line">test_data.loc[(test_data.Cabin.notnull()), <span class="string">&quot;Cabin&quot;</span>] = <span class="number">1</span></span><br><span class="line">test_data.loc[(test_data.Cabin.isnull()), <span class="string">&quot;Cabin&quot;</span>] = <span class="number">0</span></span><br></pre></td></tr></table></figure>
<p>再看看有没有缺失数据的<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/10.png"><br>行啦。<br>接下来把非数值数据转换为数值数据<br>将性别数据转换为数值数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">train_data.loc[train_data[<span class="string">&quot;Sex&quot;</span>] == <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Sex&quot;</span>] = <span class="number">0</span></span><br><span class="line">train_data.loc[train_data[<span class="string">&quot;Sex&quot;</span>] == <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Sex&quot;</span>] = <span class="number">1</span></span><br><span class="line">test_data.loc[test_data[<span class="string">&quot;Sex&quot;</span>] == <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Sex&quot;</span>] = <span class="number">0</span></span><br><span class="line">test_data.loc[test_data[<span class="string">&quot;Sex&quot;</span>] == <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Sex&quot;</span>] = <span class="number">1</span></span><br></pre></td></tr></table></figure>
<p> 将登船地点数据转换为数值数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># C:0, Q:1, S:2</span></span><br><span class="line">train_data.loc[train_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;C&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">0</span></span><br><span class="line">train_data.loc[train_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;Q&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">1</span></span><br><span class="line">train_data.loc[train_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;S&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">2</span></span><br><span class="line">test_data.loc[test_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;C&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">0</span></span><br><span class="line">test_data.loc[test_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;Q&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">1</span></span><br><span class="line">test_data.loc[test_data[<span class="string">&quot;Embarked&quot;</span>] == <span class="string">&#x27;S&#x27;</span>, <span class="string">&quot;Embarked&quot;</span>] = <span class="number">2</span></span><br><span class="line">print(train_data.head())</span><br><span class="line">print(test_data.head())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/11.png"><br>最后，提取我们认为在预测模型中重要的特征: Pclass，Sex，Age，Embarked，SibSp，Parch，Cabin<br>构建一个新的数据表。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">columns = [<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;Sex&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Embarked&#x27;</span>, <span class="string">&#x27;Survived&#x27;</span>, <span class="string">&#x27;Cabin&#x27;</span>]</span><br><span class="line"> new_train_data = train_data[columns]</span><br><span class="line"> print(new_train_data.info())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/12.png"><br>OK，可以开始建模了。<br>先用刚学的线性回归模型。<br>线性回归模型<br>特征变量</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">predictors = [<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;Sex&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Embarked&#x27;</span>, <span class="string">&#x27;Cabin&#x27;</span>]</span><br><span class="line">LR = LinearRegression()</span><br></pre></td></tr></table></figure>
<p>设置进行交叉验证</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">kf = KFold(<span class="number">5</span>, random_state = <span class="number">0</span>)</span><br><span class="line">train_target = new_train_data[<span class="string">&quot;Survived&quot;</span>]</span><br><span class="line">accuracys = []</span><br><span class="line"><span class="keyword">for</span> train, test <span class="keyword">in</span> kf.split(new_train_data):</span><br><span class="line"> LR.fit(new_train_data.loc[train, predictors], new_train_data.loc[train, <span class="string">&quot;Survived&quot;</span>])</span><br><span class="line"> pred = LR.predict(new_train_data.loc[test, predictors])</span><br><span class="line"> pred[pred &gt;= <span class="number">0.6</span>] = <span class="number">1</span></span><br><span class="line"> pred[pred &lt; <span class="number">0.6</span>] = <span class="number">0</span></span><br><span class="line"> accuracy = <span class="built_in">len</span>(pred[pred == new_train_data.loc[test, <span class="string">&quot;Survived&quot;</span>]])/<span class="built_in">len</span>(test)</span><br><span class="line"> accuracys.append(accuracy)</span><br><span class="line">print(np.mean(accuracys))</span><br></pre></td></tr></table></figure>
<p>结果:0.799083547799887<br>提交kaggle以后结果并不好。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/13.png"><br>再看看回归的具体结果。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">&quot;回归系数:&quot;</span>, LR.coef_)</span><br><span class="line">print(<span class="string">&quot;截距:&quot;</span>, LR.intercept_)</span><br><span class="line">X = new_train_data[predictors]</span><br><span class="line">y = new_train_data[<span class="string">&quot;Survived&quot;</span>]</span><br><span class="line">Y = LR.predict(X)</span><br><span class="line">print(<span class="string">&quot;模型评分:&quot;</span>, LR.score(X, y))</span><br><span class="line">i = <span class="number">241</span></span><br><span class="line"><span class="keyword">for</span> index <span class="keyword">in</span> predictors:</span><br><span class="line"> X = new_train_data[index]</span><br><span class="line"> fig = plt.subplot(i)</span><br><span class="line"> i += <span class="number">1</span></span><br><span class="line"> plt.plot(X, Y, <span class="string">&quot;*&quot;</span>)</span><br><span class="line"> plt.plot(X, y, <span class="string">&quot;o&quot;</span>)</span><br><span class="line">plt.savefig(<span class="string">&quot;LRtest.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>结果:<br>回归系数: [-0.13393963  0.50834201 -0.00505791 -0.03254537 -0.03019912 -0.02651349<br>  0.11037934]<br>截距: 0.7106465692231267<br>0.40082362319192455<br>模型的R²才0.4(越接近1越理想)。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/14.png"><br>看着也没啥联系。再看看每个回归系数的检验吧。sklearn里似乎没有相关函数，还是用statsmodels模块里的函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 看模型的假设检验</span></span><br><span class="line">X = new_train_data[predictors]</span><br><span class="line">X = sm.add_constant(X)</span><br><span class="line">model = sm.OLS(Y, X).fit()</span><br><span class="line">res = get_index(model)</span><br><span class="line">print(<span class="string">&quot;回归参数&quot;</span>, model.params)</span><br><span class="line">print(<span class="string">&quot;回归结果&quot;</span>, res)</span><br><span class="line">print(model.summary())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/15.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/13/16.png"><br>回归系数跟用sklearn算的一样，但检验结果却特别好，有点诡异。可能是因为这个问题很多变量只有少数几个值，甚至两个值，是离散变量，不适合直接用线性回归。<br>再试试其它方法。<br>本文代码: <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/titanic">https://github.com/zwdnet/MyQuant/tree/master/titanic</a><br>以后关于这个问题的代码都放到这里面。</p>
<p>我发文章的四个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的博客园博客地址： <a target="_blank" rel="noopener" href="https://www.cnblogs.com/zwdnet/">https://www.cnblogs.com/zwdnet/</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/" rel="tag"># 机器学习</a>
          
            <a href="/tags/%E5%9B%9E%E5%BD%92%E5%88%86%E6%9E%90/" rel="tag"># 回归分析</a>
          
            <a href="/tags/%E5%AE%9E%E6%93%8D/" rel="tag"># 实操</a>
          
            <a href="/tags/%E6%B3%B0%E5%9D%A6%E5%B0%BC%E5%85%8B%E5%8F%B7/" rel="tag"># 泰坦尼克号</a>
          
            <a href="/tags/kaggle/" rel="tag"># kaggle</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/03/07/%E8%A7%84%E8%8C%83%E5%8C%96%E7%89%99%E5%91%A8%E5%9F%BA%E7%A1%80%E6%B2%BB%E7%96%97/" rel="next" title="规范化牙周基础治疗">
                <i class="fa fa-chevron-left"></i> 规范化牙周基础治疗
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/07/%E5%85%A8%E7%93%B7%E6%9D%90%E6%96%99%E5%9C%A8%E5%85%A8%E5%8F%A3%E9%87%8D%E5%BB%BA%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8/" rel="prev" title="全瓷材料在全口重建中的应用">
                全瓷材料在全口重建中的应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
